package com.rub.android.dao

import com.rub.android.model.UserModel
import org.litepal.LitePal
import com.blankj.utilcode.util.ThreadUtils
import com.rub.android.utils.Task


class UserDao {


    /**
     * 异步保存
     */
    fun saveAsync(user: UserModel, callback: ((Boolean) -> Unit)? = null) {
        ThreadUtils.executeByCached(Task<Boolean>({
            save(user,false)
        }, {
            callback?.invoke(it ?: false)
        }))
    }
    /**
     * 保存
     */
    fun save(user: UserModel, isDel: Boolean): Boolean {
        if (user.userName.isNullOrBlank() || user.passWord.isNullOrBlank()) {
            return false
        }

        if (isDel) {
            val userName = user.userName
            //如果找到一条相同的就删除再插入
            LitePal.where("userName = ?", userName)?.findFirst(user::class.java)?.delete()
        }
        return user.save()
    }

    /**
     * 查询
     */
    fun getOne(uniqueKey: String?): UserModel? {
        if (uniqueKey.isNullOrBlank()) return null
        return LitePal.where("userName = ?", uniqueKey)?.findFirst(UserModel::class.java)
    }


    /**
     * 删除
     */
    fun delete(uniqueKey: String?): Boolean {
        if (uniqueKey.isNullOrBlank()) return false

        return LitePal.where("userName = ?", uniqueKey)?.findFirst(UserModel::class.java)
            ?.delete() ?: 0 > 0
    }

    /**
     * 删除所有
     */
    fun deleteAll(): Boolean {
        return LitePal.deleteAll(UserModel::class.java) > 0
    }

    /**
     * 更新
     * val cv = ContentValues()
     * cv.put("userName", userModel.userName)
     * cv.put("passWord", userModel.passWord)
     * val ret: (Long) -> Int = { LitePal.update(UserModel::class.java, cv, it) }
     * return user?.id?.let(ret)!!  > 0
     */
    fun update(userModel: UserModel): Boolean {
        //更新：方法1
        val user: UserModel? =
            LitePal.where("userName = ?", userModel.userName)?.findFirst(UserModel::class.java)
        return user?.id?.let { userModel.update(it) }!! > 0

    }


}

